#!/bin/bash
# Service Control Script For Linux Platform
# 2013-12-30

# chkconfig: 2345 85 15
# description: $0 - this script starts and stops the $name daemin
# processname: $name
# config: $conf
# pidfile: $pidfile

name=php-fpm
prefix=/usr/local/php
bin=$prefix/sbin/php-fpm
conf=$prefix/etc/php.ini
conf2=$prefix/etc/php-fpm.conf
pidfile=$prefix/var/run/php-fpm.pid
#lock=

ECHO_SUCCESS() {
echo -e "\033[60G[\033[32m OK \033[39m]"
}

ECHO_WARN() {
echo -e "\033[60G[\033[33m Warning \033[39m]"
}

ECHO_FAILED() {
echo -e "\033[60G[\033[31m Failed \033[39m]"
}

func_start() {
[ -f $pidfile ] && rm -f $pidfile
$bin -c $conf -g $pidfile -y $conf2 -D
if [ "$?" = "0" ] ; then
   ECHO_SUCCESS
else
   ECHO_FAILED
fi
}

start_prog() {
echo -n "Start $name ... "
sleep 1
if [ -f $pidfile ] ; then
  # 判断pid文件是否存在，如果存在则取得pid值
  pid=`cat $pidfile 2>/dev/null`
  if [ -z $pid ] ; then
     # 如果pid值为空则启动程序
     func_start
  else
     # 如果pid值存在则检测该pid对应的进程是否存在
     ps -p $pid 1>/dev/null 2>&1
     if [ "$?" = "0" ] ; then
        # 进程存在，提示用户
        echo -n "$name seems to be running (PID $pid). "
        ECHO_WARN
     else
        # 进程不存在直接启动程序
        func_start
     fi
  fi
else
   # pid文件不存在，直接启动程序
   func_start
fi
}

stop_prog() {
echo -n "Stop $name ... "
sleep 1
if [ -f $pidfile ] ; then
  kill `cat $pidfile 2>/dev/null`
  if [ "$?" = 0 ] ; then
    [ -f $pidfile ] && rm -f $pidfile
    ECHO_SUCCESS
  else
    ECHO_FAILED
  fi
else
  echo -n "The pid file is not exist" && ECHO_FAILED
fi
}

status_prog() {
if [ -f $pidfile ] ; then
  pid=`cat $pidfile 2>/dev/null`
  ps -p $pid 1>/dev/null 2>&1
  if [ "$?" = "0" ] ; then
    echo -n "Status: $name is running (PID $pid) ..." && ECHO_SUCCESS
  else
    echo -n "Status: $name is stoped ... " && ECHO_SUCCESS
  fi
else
  name0=`echo $name | awk '{print tolower($1)}'`
  #ps -C $name0 1>/dev/null 2>&1
  ps -ef | grep $name0 | grep -Ev "grep|status" >/dev/null 2>&1
  if [ $? = 0 ] ; then
    echo -n "Status: $name is running ... The pid file is not exist" && ECHO_WARN
  else
    echo -n "Status: $name is stoped ... " && ECHO_SUCCESS
  fi
fi
}

case $1 in
  start)
        start_prog
  ;;
  stop)
        stop_prog
  ;;
  status)
	status_prog
  ;;
  reload|restart)
        stop_prog
        start_prog
  ;;
  *)
        echo "Usage: service `basename $0` start|stop|status|reload|restart"
esac   

